﻿#ifndef PST_TABLEDATAITEMDELEDATE_H
#define PST_TABLEDATAITEMDELEDATE_H

#include <QStyledItemDelegate>
#include <QEvent>
#include <QAbstractItemModel>
#include <QStyleOptionViewItem>
#include <QModelIndex>
#include <QMouseEvent>
#include <QApplication>
#include <QDebug>
#include <QObject>

namespace pst
{
    class TableDataItemDelegate : public QStyledItemDelegate
    {
        Q_OBJECT

    public:
        bool editorEvent(QEvent* event,
                         QAbstractItemModel* model,
                         const QStyleOptionViewItem& option,
                         const QModelIndex& index) override
        {
            if (event->type() == QEvent::MouseButtonPress)
            {
                QMouseEvent* me = static_cast<QMouseEvent*>(event);

                // 获取图标和文本的矩形区域
                QStyleOptionViewItem opt = option;
                initStyleOption(&opt, index);

                QRect iconRect = QApplication::style()->subElementRect(
                    QStyle::SE_ItemViewItemDecoration, &opt, option.widget);

                QRect textRect = QApplication::style()->subElementRect(
                    QStyle::SE_ItemViewItemText, &opt, option.widget);

                // 判断点击位置
                if (iconRect.contains(me->pos()))
                {
                    emit signal_iconClicked(index);
                    return true;
                }
                else if (textRect.contains(me->pos()))
                {
                    emit signal_itemClicked(index);
                    return true;
                }
            }
            return QStyledItemDelegate::editorEvent(event, model, option, index);
        }

    public:
        TableDataItemDelegate();
        TableDataItemDelegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) {};

    signals:
        void signal_iconClicked(const QModelIndex& index); // 图标点击信号
        void signal_itemClicked(const QModelIndex& index); // Item点击信号

    };
}
#endif
